//
//  CommentMsgDetailViewController.m
//  LiveStar
//
//  Created by 漪珊 on 2017/5/17.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "CommentMsgDetailViewController.h"
#import "MessageCommentCell.h"
#import "CommentMsgTopView.h"
#import "CommentNoticeModel.h"
#import "TrendReplyModel.h"

@interface CommentMsgDetailViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
    NSDictionary *_contentDitc;
    NSMutableArray *_replyListArray;
    UITextField *_msgInputFeild;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) CommentMsgTopView *topView;
@property (nonatomic, strong) UIView *msgInputView;
@property (nonatomic, copy) NSString *parentId;
@property (nonatomic, copy) NSString *parentudid;
@end

@implementation CommentMsgDetailViewController

- (UIView *)msgInputView {
    if (!_msgInputView) {
        //输入框
        _msgInputView = [[UIView alloc] initWithFrame:CGRectMake(0, kSCREEN_HEIGHT -kNAV_HEIGHT- 50, kSCREEN_WIDTH, 50 )];
        _msgInputView.backgroundColor = [UIColor whiteColor];
        UIView *sepline = [[UIView alloc] init];
        [_msgInputView addSubview:sepline];
        sepline.frame = CGRectMake(0, 0, kSCREEN_WIDTH, 0.5);
        sepline.backgroundColor = [UIColor cellLineColor];
        UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        sendBtn.frame = CGRectMake(self.view.width - 15 - 50, 0, 50, 50);
        [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
        [sendBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [sendBtn setTitleColor:UIColorFromRGB(0x0ACCAC) forState:UIControlStateNormal];
        [sendBtn setBackgroundColor:[UIColor clearColor]];
        [sendBtn addTarget:self action:@selector(clickSend:) forControlEvents:UIControlEventTouchUpInside];
        
        _msgInputFeild = [[UITextField alloc] initWithFrame:CGRectMake(10,7.5,sendBtn.left - 20,30)];
        _msgInputFeild.backgroundColor = [UIColor clearColor];
        _msgInputFeild.returnKeyType = UIReturnKeySend;
        _msgInputFeild.borderStyle = UITextBorderStyleRoundedRect;
        _msgInputFeild.placeholder = @"留下你想说的";
        _msgInputFeild.delegate = self;
        _msgInputFeild.textColor = [UIColor blackColor];
        _msgInputFeild.font = [UIFont systemFontOfSize:14];
        
        [_msgInputView addSubview:_msgInputFeild];
        [_msgInputView addSubview:sendBtn];
        
    }
    return _msgInputView;
}


#pragma mark -- Request
//获取回复详情
- (void)CommentDetailRequest {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN,
                           @"parent":[kUSER_TYPE intValue] == 100 ?self.commentNoticeModel.cid : self.commentNoticeModel.c_parent,
                           @"page":@"1"
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kMessageTrendReply];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            NSDictionary *contentDict = responseObject[@"data"];
            _contentDitc = [NSDictionary dictionaryWithDictionary:contentDict];
            NSArray *imagesArray = [responseObject[@"data"][@"c_images"] componentsSeparatedByString:@","];
            self.topView.c_nameLabel.text = contentDict[@"u_nickname"];
            [self.topView.trendImgsView sd_setImageWithURL:[NSURL URLWithString:imagesArray[0]] placeholderImage:kPLACE_MID];
            self.topView.c_contentLabel.text = contentDict[@"mycontent"] ?contentDict[@"mycontent"] : @"";
            [self.topView.c_IconImgView sd_setImageWithURL:[NSURL URLWithString:contentDict[@"u_avatar"]] placeholderImage:kPlACE_ICON];
            self.topView.c_timeLabel.text = contentDict[@"c_createtime"];
            self.topView.imgCountLabel.text = [NSString stringWithFormat:@"共%lu张",(unsigned long)imagesArray.count];
            self.topView.detailLabel.text = contentDict[@"c_content"];
            self.topView.titleLabel.text = [NSString stringWithFormat:@"%@发布了图文",contentDict[@"sname"]];
            NSArray *array = responseObject[@"data"][@"list"];
            for (NSDictionary *replyDict in array) {
                TrendReplyModel *model = [[TrendReplyModel alloc] initWithDict:replyDict];
                [_replyListArray addObject:model];
            }
            [self.tableView reloadData];
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}
//发送回复 20
- (void)SendReplyWordRequestWithContent:(NSString *)content ParentID:(NSString *)parenetId ParentUdid:(NSString *)parentudid {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN,
                           @"cid":_contentDitc[@"c_cid"],
                           @"description":content,
                           @"type":@"20",
                           @"parent":_contentDitc[@"cid"],
                           @"pudid":self.commentNoticeModel.c_udid
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kSendComment];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            [self showTitle:responseObject[@"data"][@"message"]];
            [self.tableView reloadData];
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self CommentDetailRequest];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameDidChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [self setUpUI];
}

#pragma mark -- UI
- (void)setUpUI {
    _replyListArray = [NSMutableArray arrayWithCapacity:1];
    self.navigationItem.title = @"回复详情";
    [self creatTableView];
    [self.view addSubview:self.msgInputView];
}
//监听键盘高度变化
-(void)keyboardFrameDidChange:(NSNotification*)notice
{
    NSDictionary * userInfo = notice.userInfo;
    NSValue * endFrameValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect endFrame = endFrameValue.CGRectValue;
    [UIView animateWithDuration:0.25 animations:^{
        _msgInputView.y = endFrame.origin.y - _msgInputView.height - kNAV_HEIGHT;
    }];
}
- (void)creatTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT-kNAV_HEIGHT - 50)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.topView = [[NSBundle mainBundle] loadNibNamed:@"CommentMsgTopView" owner:self options:nil].lastObject;
    self.topView.frame = CGRectMake(0, 0, kSCREEN_WIDTH, 170);
    self.tableView.tableHeaderView = self.topView;
    self.topView.trendDetailAction = ^(){
        
    };
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.tableView];
}

#pragma mark -- tableView 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _replyListArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageCommentCell *cell = [MessageCommentCell loadNibCellWithTabelView:tableView];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    TrendReplyModel *model = _replyListArray[indexPath.row];
    cell.trendReplyModel = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark -- 区头视图

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    TrendReplyModel *model = _replyListArray[indexPath.row];
    CGSize maxSize = CGSizeMake(kSCREEN_WIDTH - 79, MAXFLOAT);
    
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14], NSForegroundColorAttributeName: [UIColor colorWithWhite:0.263 alpha:1.000]};
    CGSize textSize = [model.c_content boundingRectWithSize:maxSize
                                                        options:NSStringDrawingUsesLineFragmentOrigin
                                                     attributes:attributes
                                                        context:nil].size;
    CGSize richTextSize = CGSizeMake(textSize.width, textSize.height + 2);
    return richTextSize.height + 10;
}

#pragma mark -- 发送评论回复
- (void)clickSend:(UIButton *)sender {
    if (_msgInputFeild.text.length) {
        [self SendReplyWordRequestWithContent:_msgInputFeild.text ParentID:@"" ParentUdid:@""];
    } else {
    }
}

#pragma mark -- UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [textField resignFirstResponder];
    
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
